//
//  PhotoManager.swift
//  SwiftChatUI
//
//  Created by xzk on 2019/2/26.
//  Copyright © 2019年 xzk. All rights reserved.
//

import UIKit
import Photos

let PhotoShouldReloadPhotosNotification = Notification.Name.init("PhotoShouldReloadPhotosNotification")

class PhotoManager: NSObject {
    static let shared = PhotoManager()
        
    private override init() {
        super.init()
        
        if !hasAuth() {
            PHPhotoLibrary.requestAuthorization { (status) in
                if status == .authorized {
                    DispatchQueue.main.async {
                        NotificationCenter.default.post(Notification(name: PhotoShouldReloadPhotosNotification))
                    }
                }
            }
        }
    }
    
    // 权限检测
    public func hasAuth() -> Bool {
        let status = PHPhotoLibrary.authorizationStatus()
        if status == .authorized {
            return true
        } else {
            return false
        }
    }
    
    // 获取所有相册
    public func albums(complete: @escaping (_ array: [AlbumModel])-> ()) {
        
        var dataArray: [AlbumModel] = []
        
        // PHAssetCollection 表示一组图片或者视频资源
        let albums = PHAssetCollection.fetchAssetCollections(with: .smartAlbum, subtype: .any, options: nil)
        albums.enumerateObjects { (collection, index, pointer) in
            // 所有图片
            let fetchResult = PHAsset.fetchAssets(in: collection, options: nil)
            if fetchResult.count > 0 {
                let asset = fetchResult.lastObject  // 最新的一张图
                
                let opt = PHImageRequestOptions()
                opt.isSynchronous = true    // 同步获取图片，只返回1张图片
                
                let manager = PHImageManager()
                manager.requestImageData(for: asset!, options: opt, resultHandler: { (data, dataUTI, orientation, info) in
                    let result = UIImage(data: data ?? Data())
                    var model = AlbumModel()
                    model.albumNamge = collection.localizedTitle ?? ""
                    model.firstImage = result
                    model.imageNum = fetchResult.count
                    model.fetchResult = fetchResult
                
                    dataArray.append(model)
                })
            }
        }
        
        complete(dataArray)
    }
    
    // 获取相册中的图片
    public class func pictures(_ album: AlbumModel, complete: @escaping (_ array: [PictureModel]) -> ()) {
        let fetchResult = album.fetchResult!
        
        var images: [PictureModel] = []
        
        if fetchResult.count == 0 {
            complete(images)
        } else {

            fetchResult.enumerateObjects { (asset, index, pointer) in
                images.append(PictureModel(asset: asset))
            }
            
            complete(images)
        }
    }
}
